package jrain.fw.http.common.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jrain.fw.http.common.consts.HttpCfg;
import jrain.fw.http.common.consts.HttpConsts;
import jrain.fw.http.common.pipeline.DefaultHttpPipelineHandler;
import jrain.fw.http.common.pipeline.HttpPipeline;

/**
 * <pre>
 * 作者：3244924214@qq.com 
 * 描述：调整处理类
 * </pre>
 */
public class DispatcherServlet extends HttpServlet {

	private static final long serialVersionUID = 5766349180380479888L;
	private static final HttpPipeline pipeline = new DefaultHttpPipelineHandler();

	public DispatcherServlet() {
	}

	protected void setEncoding(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
	}

	protected void setCros(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader(HttpConsts.AccessControlAllowOrigin, HttpCfg.httpCorsOrigin.getValue());
		response.setHeader(HttpConsts.AccessControlAllowMethods, HttpCfg.httpCorsMethods.getValue());
		response.setHeader(HttpConsts.AccessControlAllowHeaders, HttpCfg.httpCorsHeaders.getValue());
	}

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		setEncoding(request, response);
		setCros(request, response);
		if ("OPTIONS".equals(request.getMethod())) {
			return;
		}
		if ("/".equals(request.getRequestURI())) {
			request.getRequestDispatcher("/index.html").forward(request, response);
		}else{
			doAfeter(request, response);
		}
	}

	protected void doAfeter(HttpServletRequest request, HttpServletResponse response) {
		getPipeline().handler(request, response);
	}

	protected HttpPipeline getPipeline() {
		return pipeline;
	}
}